//
//  UIImage+compress.swift
//  ShareCar
//
//  Created by lishuai on 2018/7/4.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation

extension UIImage {
    func compress(maxSizeKBytes size: Double) -> Data {
        var data = UIImageJPEGRepresentation(self, 1.0)!
        var dataKBytes = Double(data.count) / 1000.0
        var maxQuality = 0.9
        var lastData = dataKBytes
        while (dataKBytes > size && maxQuality > 0.01) {
            maxQuality = maxQuality - 0.01
            data = UIImageJPEGRepresentation(self, CGFloat(maxQuality))!
            dataKBytes = Double(data.count) / 1000.0
            if lastData == dataKBytes {
                break
            } else {
                lastData = dataKBytes
            }
        }
        return data
    }
}
